<?php

namespace backend\controllers;

use backend\models\JjrProjectHouse;
use backend\models\JjrUserProject;
use Yii;
use backend\models\JjrProject;
use yii\base\Exception;
use yii\data\ActiveDataProvider;
use backend\controllers\BaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * JjrProjectController implements the CRUD actions for JjrProject model.
 */
class JjrProjectController extends BaseController
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                  //  'delete' => ['POST'],
                ],
            ],
        ];
    }
    public function actionSearch($q=''){
        $out = ['results' => ['id' => '', 'text' => '']];
        $query = JjrProject::find()->alias('p');

        if($q){
            $query->andFilterWhere(['like', 'p.name', $q]);
        }
        $projects =  $query->select('p.name,p.id')->asArray()->all();
        foreach ($projects as &$project) {
            $project['text'] = $project['name'];
        }
        $out['results'] = $projects;
        return $this->ajaxReturn($out);
    }


    /**
     * Lists all JjrProject models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => JjrProject::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single JjrProject model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new JjrProject model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new JjrProject();
        $house = new JjrProjectHouse();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $data = Yii::$app->request->post()['JjrProject'];
            $realPics = isset($data['real_pic'])?$data['real_pic']:null;
            $vrPics =  isset($data['vr_pic'])?$data['vr_pic']:null;
            $aroundPics =  isset($data['around_pic'])?$data['around_pic']:null;
            if(is_array($realPics)){
                $model->real_pic = implode(',',$realPics);
            }
            if(is_array($vrPics)){
                $model->vr_pic = implode(',',$vrPics);
            }
            if(is_array($aroundPics)){
                $model->around_pic = implode(',',$aroundPics);
            }
            $model->save(false);
            return $this->redirect(['view', 'id' => $model->id]);
        }
       // $errors = $model->getErrors();
       // print_r($errors);exit;
        return $this->render('create', [
            'model' => $model,
            'house'=>$house
        ]);
    }

    /**
     * Updates an existing JjrProject model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $data = Yii::$app->request->post()['JjrProject'];
            $realPics = isset($data['real_pic'])?$data['real_pic']:null;
            $vrPics =  isset($data['vr_pic'])?$data['vr_pic']:null;
            $aroundPics =  isset($data['around_pic'])?$data['around_pic']:null;
            if(is_array($realPics)){
                $model->real_pic = implode(',',$realPics);
            }
            if(is_array($vrPics)){
                $model->vr_pic = implode(',',$vrPics);
            }
            if(is_array($aroundPics)){
                $model->around_pic = implode(',',$aroundPics);
            }
            $model->save(false);
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing JjrProject model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {

        $userProject = JjrUserProject::findOne(['jjr_project_id'=>$id]);
        if($userProject){
            $this->error("删除失败，已有客户跟进");
        }
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the JjrProject model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return JjrProject the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = JjrProject::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

        public function actionAudit($id){
            $model =$this->findModel($id);
            $model->updateAttributes(['status'=>1]);
            return $this->redirect(['index']);
        }
    public function actionCancelAudit($id){
           $model =$this->findModel($id);
        $model->updateAttributes(['status'=>0]);
        return $this->redirect(['index']);
    }
}
